// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import VueAxios from 'vue-axios';
// 设置axios支持set cookies
axios.defaults.withCredentials = true;
// 添加axios全局拦截器-请求
axios.interceptors.request.use(function (config) {
  if (localStorage.getItem('token')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = localStorage.getItem('token');
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});
//返回拦截器
axios.interceptors.response.use(function (response) {
  // 只有当auth存在时候才更新token,防止请求首页报表时候清空token
  if(response.headers["account-session-id"]){
    localStorage.setItem('token',response.headers["account-session-id"])
  }
  return response;
}, function (error) {
  if  (401 === error.response.status) {
    localStorage.removeItem('token');
    window.location = '/';
  }
  return Promise.reject(error);
});
Vue.use(VueAxios, axios);
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (!token || token === null) {
    if(to.path !== '/login') {
      next('/login');
    } else {
      next()
    }
  } else {
    // new webSocket
    if(Vue.ws === undefined) {
      if(to.path === '/login') {
        next()
      } else {
        //生产环境websocket地址从服务器获取
        if(process.env.NODE_ENV === 'production') {
          let HOST='ws';
          if(location.origin.includes('https://')){
            HOST='wss';
          }
          Vue.ws = new WebSocket(HOST+"://"+location.host+"/wx_gateway/debugging/v1/websocket?authorization="+localStorage.getItem('token'));
        } else {
          Vue.ws = new WebSocket("ws://wx.bmgf.com.cn/wx_gateway/debugging/v1/websocket?authorization="+localStorage.getItem('token'));
        }
        next();
      }
    } else {
      if(to.path === '/login') {
        next('/list');
      } else {
        next()
      }
    }
  }

});
Vue.filter('currency', function (value) {
  const l10nCNY = new Intl.NumberFormat("zh-CN", { style: "currency", currency: "CNY" })
  if (value !== null) {
    return l10nCNY.format(value);
  }
});
console.log("%c", "color:red;font-size:30px;font-weight:bolder;padding:20px 20px;line-height:10px;background:url('http://img.zcool.cn/community/0127c0577e00620000012e7e12da0e.gif') repeat-x;background-size:contain;");

Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
  el: '#app',
  data() {
    return {
      IPConfig: {
        http: 'http://',
        HOST: 'wx.bmgf.com.cn',
        PORT: '80'
      },
      museList: [],
      infoList: [],
      infoUrl: ''
    }
  },
  router,
  template: '<App/>',
  // components: { App }
  render: h => h(App)
});
